package Concurrency4_GeekTime.Chapter01_BackGround;

import java.util.concurrent.*;

/**
 * 功能说明：
 * 开发人员：@author MaLi
 */
public class Base02_Atomicity {
    //use volatile key word still exists problem
    private static /*volatile*/ int sum = 0;
    private static int times = 10000;

    public static void main(String[] args) {
        // Way1
        /*Thread t1 = new Thread(() ->add1());
        Thread t2 = new Thread(() ->add1());
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(sum);*/

        // Way2
        /*ExecutorService service = Executors.newFixedThreadPool(2);
        Future<?> f1 = service.submit(() -> add1());
        Future<?> f2 = service.submit(() -> add1());
        try {
            f1.get();
            f2.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(sum);*/

        CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> add1());
        CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> add1());
        CompletableFuture<Integer> f3 = f1.thenCombine(f2, (f1r, f2r) -> {
            return sum;
        });
        f3.join();
        try {
            Integer integer = f3.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    public static void add1() {
        for (int i = 0; i < times; i++) {
            sum+=1;
        }
    }
}
